<template>
  <div class="saveUploadBox">
    <el-upload
      ref="imgRef"
      accept="image/png, image/jpg, image/jpeg,application/pdf"
      name="file"
      list-type="picture-card"
      :limit="limitNum"
      :action="uploadApi"
      :file-list="fileList"
      :isRead="isRead"
      :before-upload="beforeUpload"
      :on-change="handleChange"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :on-error="handleError"
    >
      <div slot="file" slot-scope="{ file }">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>

          <span
            v-if="!isRead"
            class="el-upload-list__item-delete"
            @click="handleRemove(file, fileList)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
      <i class="el-icon-plus"></i>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="showPic" />
    </el-dialog>
    <p class="pTxt">只能上传jpg/png/pdf格式文件</p>
  </div>
</template>

<script>
import Const from "@/api/Const.js";
export default {
  name: "PictureUpload",
  watch: {
    initPics(val) {
      this.initFileList();
    }
  },
  other: {
    //深度观察对象
    handler(val) {},
    deep: true
  },
  props: {
    certificateId: {
      type: String,
      default: ""
    },
    limitNum: {
      type: Number,
      default: 1
    },
    limitSize: {
      type: Number,
      default: 10
    },
    uploadApi: {
      type: String,
      default: ""
    },
    isRead: {
      type: Boolean,
      default: ""
    },
    initPics: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      showUpload: true,
      dialogVisible: false,
      fileList: [], //当前页面显示的图片列表
      picList: [], //用于保存符合格式的当前页面显示的图片列表
      picStr: "",
      showPic: ""
    };
  },
  mounted() {},
  methods: {
    initFileList() {
      const params = this.initPics;
      if (params.length > 0) {
        var url = "";
        this.fileList = params.split(";").map(value => {
          return { url: this.qianxunbaseImgUrls + value };
        });
      }
      this.hideOrShowAddMoreIcon(this.fileList);
    },
    beforeUpload(file) {
      return this.checkBeforeUpload(file);
    },
    handleChange(file, fileList) {
      if (file.raw.type == 'application/pdf') {
        file.url = 'static/images/logo.png';
      }
    },
    handleExceed(file, fileList) {
      this.$message({
        message: "最多上传" + this.limitNum + "张",
        type: "warning"
      });
    },
    handlePreview(file) {
      this.dialogVisible = true;
      this.showPic = file.url;
    },
    handleSuccess(res, file, fileList) {
      let arr = [];
      // let oldPicStr = this.picStr
      arr.push(res);
      this.picList = arr;
      this.$emit("getImgUrl", file.response);
      this.hideOrShowAddMoreIcon(fileList);

      if (file.response) {
        this.picStr = file.response;
        this.getCoverImgPath(file.response);
      }
    },

    getCoverImgPath(url) {
      var that = this;
      console.log(this.certificateId, "certificateIdcertificateId");
      this.$axios
        .get(Const.api.getDetails, {
          params: {
            url: url,
            certificateId: this.certificateId
          }
        })
        .then(res => {
          if (res.data.code == 0) {
            let info = JSON.parse(res.data.data);
            this.$emit("getUploadData", {
              info: info.items,
              img: this.picStr
            });
            console.log(info, "upload");
          } else {
            that.$message({
              message: "无法识别图片！",
              type: "warm"
            });
            this.$emit("getUploadData", {
              img: this.picStr
            });
          }
        });
    },
    handleRemove(file, fileList) {
      var self = this;
      this.$confirm("确定删除Layout图片吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let arr = [];
          fileList.forEach(element => {
            let url = "";
            if (typeof element.response != "undefined") {
              url = element.response.data.name;
            } else {
              url = element.url.split("=")[1];
            }
            if (url != undefined) {
              arr.push(url);
            }
          });
          self.fileList = [];
          fileList = [];
          self.picList = [];
          self.$emit("getUploadData", {});
          self.hideOrShowAddMoreIcon(fileList);
        })
        .catch(() => {});
    },
    handleError(err, file, fileList) {
      this.hideOrShowAddMoreIcon(fileList);
    },
    checkBeforeUpload(file) {
      const isJPGorPNG = file.type;
      const isLt = file.size / 1024 / 1024 < this.limitSize;
      var flag = true;
      if (isJPGorPNG !== "image/jpeg" && isJPGorPNG !== "image/png" && isJPGorPNG !== "application/pdf") {
        this.$message.error("上传图片只能是JPG、PNG或者PDF格式!");
        flag = false;
      }
      if (!isLt) {
        this.$message({
          showClose: true,
          message:
            "图片: " +
            file.name +
            " 不能超过" +
            this.limitSize +
            "M，请压缩后再上传！",
          type: "warning"
        });
        flag = false;
      }
      return flag;
    },
    removeFileListHandle() {
      this.fileList = [];
    },

    hideOrShowAddMoreIcon(fileList) {
      let box = this.$refs.imgRef.$el.children[1];
      if (box) {
        if (this.isRead) {
          box.style.display = "none";
        } else {
          if (fileList.length >= this.limitNum) {
            box.style.display = "none";
          } else {
            box.style.display = "inline-block";
          }
        }
      }
    }
  }
};
</script>

<style lang="scss">
.saveUploadBox {
  .el-upload--picture-card {
    width: 500px;
    height: 333px;
    .el-icon-plus {
      font-size: 28px;
      color: #8c939d;

      line-height: 333px;
      text-align: center;
    }
  }
  .el-upload-list--picture-card .el-upload-list__item {
    width: 500px !important;
    height: 333px !important;
  }
  .pTxt {
    text-align: center;
  }
}
.disabled .el-upload--picture-card {
  display: none;
}
</style>
